from pynput import keyboard
import queue
import time
import threading
import asyncio, asyncvnc
from enum import Enum

'''

'''
async def VNCconsumer():
    async with asyncvnc.connect('localhost') as client:
        while True:
            # 从线程安全元组取出鼠标要移动到的xy坐标，并移动鼠标
            mousePos = mousePositionTuple.get()
            if len(mousePos) !=0 :
                client.mouse.move(mousePos[0], mousePos[1])
            # 按下按键
            with client.mouse.hold(2):
                # 等待keyboard线程发送更新按键按下情况的消息给我
                vncHoldCallEvent.wait()
            # 离开with代码块，此时所有按键被VNC释放，然后重新从循环头部进入时，按键会被client.keyboard.hold方法再次按下
            # 重置event，使得event.wait()起到阻塞作用
            vncHoldCallEvent.clear()

# mouse的消费者线程
class ConsumerThread(threading.Thread):
    def __init__(self, name):
        super().__init__()
        self.name = name

    def run(self):
        print('Thread: {} start at {}'.format(self.name, time.ctime(time.time())))

        # 启动VNC协程（这个协程内部会阻塞线程。这个写法很屎，但我不熟悉协程，python多线程，keyboard库，asyncVNC这些代码，所以暂时想不出更好的）
        asyncio.run(VNCconsumer())

class ThreadSafeTuple:
    def __init__(self, initial_value=()):
        self._value = initial_value
        self._lock = threading.Lock()

    def get(self):
        with self._lock:
            return self._value

    def set(self, new_value):
        if not isinstance(new_value, tuple):
            raise ValueError("new_value must be a tuple")
        with self._lock:
            self._value = new_value

mousePositionTuple = ThreadSafeTuple()

vncHoldCallEvent = threading.Event()
vncHoldCallEvent.clear()

threads = []
[threads.append(ConsumerThread(str(i))) for i in range(1,2)]

# 启动所有线程
[t.start() for t in threads]


# 在主线程启动标准输入
while True:
    try:
        # 从标准输入读取一行文本
        line = input("请输入两个数字，中间用空格隔开（输入'exit'退出）：")
        if line == 'exit':
            break

        # 按空格分割文本，得到两个字符串
        num_str1, num_str2 = line.split()

        # 将字符串转换为整数
        num1 = int(num_str1)
        num2 = int(num_str2)

        # 打印这两个数字
        print("x坐标是：", num1)
        print("y坐标是：", num2)

        new_tuple = (num1, num2)
        # 将XY坐标设置到线程安全元组中
        mousePositionTuple.set(new_tuple)

        vncHoldCallEvent.set()
    except ValueError:
        print("输入格式错误，请确保输入两个数字，中间用空格隔开。")

